import React from 'react'
import { Button, Icon, Input, Table, Tag } from 'antd'
import Highlighter from 'react-highlight-words'

import _ from 'lodash'
import { FormattedMessage } from 'react-intl'

export default class ProgramAssignmentsBox extends React.Component {
  state = {
    searchText: ''
  }
  uniqByAssTag = groupByTopicAssignmentsTag => {
    return _.uniqBy(groupByTopicAssignmentsTag[Object.keys(groupByTopicAssignmentsTag)[0]], item => item.assTag)
      .filter(item => !!item.assTag)
      .map(item => item.assTag)
  }
  getColumns = groupByTopicAssignmentsTag => {
    let uniqByAssTags = this.uniqByAssTag(groupByTopicAssignmentsTag)

    const columns = [{
      title: <FormattedMessage id='主题'/>,
      dataIndex: 'topicTitle',
      width: 80,
      render: (text,record) => {
        return <a onClick={()=>this.props.onChangeTopic(text,record.userTag)}>{text}</a>
      }
    }, {
      title: 'Tag',
      dataIndex: 'userTag',
      width: 80,
      ...this.getColumnSearchProps('userTag'),
      sorter: (a, b) => a - b < 0,
      render: (item) => {
        return <span>{this.formatTags(item)}</span>
      }
    }]
    uniqByAssTags.forEach(item => columns.push({
      title: <font color={item.split('|')[1]}>{item.split('|')[0]}</font>,
      dataIndex: item,
      width: 100,
      render: (text) => {
        return <font color={item.split('|')[1]}>{text}</font>
      }
    }))
    return columns
  }

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
      <div style={{padding: 8}}>
        <Input
          ref={node => {
            this.searchInput = node
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{width: 188, marginBottom: 8, display: 'block'}}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{width: 90, marginRight: 8}}
        >
          Search
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{width: 90}}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{color: '#1890ff'}}/>
    ),
    onFilter: (value, record) =>
      (record[dataIndex] || '')
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    },
    render: text => (
      <Highlighter
        highlightStyle={{backgroundColor: '#ffc069', padding: 0}}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  })

  handleSearch = (selectedKeys, confirm) => {
    confirm()
    this.setState({searchText: selectedKeys[0]})
  }

  handleReset = clearFilters => {
    clearFilters()
    this.setState({searchText: ''})
  }

  formatTags = (item) => {
    if (!item) return ''
    const tagColors = item.split(',')

    return tagColors.map((item, index) => {
      const tagColor = item.split('|')
      return <Tag color={tagColor[1]} key={index}>{tagColor[0]}</Tag>
    })
  }
  getData = groupByTopicAssignmentsTag => {
    let result = []
    let uniqByAssTags = this.uniqByAssTag(groupByTopicAssignmentsTag)
    const topicsTitle = Object.keys(groupByTopicAssignmentsTag)
    topicsTitle.forEach(topicTitle => {
      const currentTopicTagsStatus = groupByTopicAssignmentsTag[topicTitle]
      const userTags = _.uniqBy(currentTopicTagsStatus, item => item.userTag)
        .filter(item => !!item.userTag).map(item => item.userTag)
      userTags.forEach(userTag => {
        let temp = {topicTitle, userTag}
        uniqByAssTags.forEach(assTag => {
          const assTagCount = currentTopicTagsStatus.filter(item => item.assTag === assTag && item.userTag === userTag)
            .reduce((value, current) => {
              value += current.assTagCount ? current.assTagCount : 0
              return value
            }, 0)
          temp[assTag] = assTagCount
        })
        result.push(temp)
      })
    })
    return result
  }
  render () {
    const {programStudentAssignmentsTag} = this.props
    let groupByTopicAssignmentsTag = _.groupBy(programStudentAssignmentsTag, item => item.topicTitle)
    const columns = this.getColumns(groupByTopicAssignmentsTag)
    const data = this.getData(groupByTopicAssignmentsTag)

    return <Table columns={columns}
                  dataSource={data}
                  pagination={false}
                  bordered
                  size='small'
    />
  }
}
